import json
from flask import Blueprint, current_app, request
import requests
from utilsapp.mysql_con import db_pagelist, db_fetchone, db_delete, db_update,db_insert
from utilsapp.common import assign_value, parsing_data_id
from datetime import datetime, timedelta

bluePrint = Blueprint('algorithm_notice', __name__)
tableName = 'algorithm_notice'

@bluePrint.route('/getlist', methods=["post"])
def table_list():
    a = request.json
    scoped = parsing_data_id(0, request)
    query = ' '
    if scoped != '':
        query += f"and {scoped}"
    sql_ = f"select n.*,d.zone_id,d.factory_id,d.company_id,d.group_id from algorithm_notice n LEFT JOIN device d on n.device_id = d.id where n.sent_time >= NOW() - INTERVAL 1 DAY{query} order by n.sent_time desc"
    res = db_pagelist(sql_, 1)
    return res

@bluePrint.route('/xj', methods=["post"])
def xj():
    sql = f"SELECT * FROM xj_mqtt WHERE target = '{request.json['name']}' AND stage IS NULL ORDER BY id DESC"
    res = db_pagelist(sql, 1, 999)
    return res

@bluePrint.route('/affair', methods=["post"])
def affair():
    sql = f"SELECT * FROM xj_mqtt WHERE target = '{request.json['name']}' ORDER BY id DESC" if request.json['type'] == '全部事务' else f"SELECT * FROM xj_mqtt WHERE target = '{request.json['name']}' and type = '{request.json['type']}' ORDER BY id DESC"
    res = db_pagelist(sql, 1, 999)
    return res

@bluePrint.route('/ignore', methods=["post"])
def ignore():
        return db_update('xj_mqtt',{'stage':'已忽略'},f"where id =%s", {"id": request.json['id']})


@bluePrint.route('/add', methods=['POST'])
def project_add():
    if 'isRport' in request.json:
        if request.json['isRport']:
            specified_date = datetime.strptime(request.json['sent_time'], "%Y-%m-%d %H:%M:%S")
            two_days_ago = specified_date - timedelta(days=2)
            # two_days_after = specified_date + timedelta(days=2)
            format = "%Y-%m-%d %H:%M:%S"
            fault_message = {
                "type_": 1,
                "device_ids": [request.json['device_id']],
                "times": [two_days_ago.strftime(format),specified_date.strftime(format)]
            }
            json_data = json.dumps(fault_message)  # 设置请求头  # 发送POST请求
            headers = {'Content-Type': 'application/json'}
            ip = current_app.config['settings']['webapi-ip']
            host = current_app.config['settings']['webapi-host']
            response = requests.post(f'http://{ip}:{host}/api/report/down/sys', data=json_data, headers=headers)
        del request.json['isRport']
    return db_insert(tableName, request.json)



@bluePrint.route("/edit", methods=['post'])
def edit():
    id_ = assign_value(request.json, "id")
    keys_not_add = ['id','company_id','factory_id','group_id','zone_id']
    addModel = {key: request.json[key]
                    for key in request.json if key not in keys_not_add}
    return db_update(tableName,addModel,f"where id =%s", {"id_": id_})
